package com.ruicar.afs.cloud.apply.pre.loan.mq.sender.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.apply.business.mq.config.ArchiveConfig;
import com.ruicar.afs.cloud.apply.business.service.ApplyRecordDetailsService;
import com.ruicar.afs.cloud.apply.business.service.ArchiveMQService;
import com.ruicar.afs.cloud.apply.common.entity.*;
import com.ruicar.afs.cloud.apply.common.feign.Apply2CaseFeign;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConfig;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.contract.enums.CertTypePictureEnum;
import com.ruicar.afs.cloud.apply.pre.approve.service.PreApproveService;
import com.ruicar.afs.cloud.apply.pre.loan.condition.CaseSubmitInfoCondition;
import com.ruicar.afs.cloud.apply.pre.loan.condition.ContractCancelCondition;
import com.ruicar.afs.cloud.apply.pre.loan.mq.sender.CaseSubmitInfoSender;
import com.ruicar.afs.cloud.apply.pre.loan.mq.sender.impl.CaseSubmitInfoServiceImpl;
import com.ruicar.afs.cloud.apply.pre.loan.mq.sender.service.CaseSubmitInfoService;
import com.ruicar.afs.cloud.apply.pre.loan.service.*;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.ApproveRefuseReasonEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.BusinessStateInEnum;
import com.ruicar.afs.cloud.common.modules.dto.mq.approve.*;
import com.ruicar.afs.cloud.common.mq.rabbit.message.AfsTransEntity;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.entity.ComAttachmentManagement;
import com.ruicar.afs.cloud.image.mapper.ComAttachmentManagementMapper;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.parameter.commom.enums.AssetChangeEnums;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>description：</p>
 * 提交案件信息（申请提交、加急、资产变更、复议申请、撤回申请）
 *
 * @author 耿继辉
 */
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/applyReport")
@ConditionalOnProperty(prefix = "com.ruicar.afs.cloud.mq.rabbit", name = "enable")
public class CaseSubmitController {

    private final ComAttachmentFileService comAttachmentFileService;
    private final CaseSubmitInfoSender caseSubmitInfoSender;
    private final CaseSubmitInfoService submitInfoService;
    private final ApplyProductService applyProductService;
    private final ApplyReportService applyReportService;
    private final ApplyOrderInfoService applyOrderInfoService;
    private final ApplyCustBaseInfoService applyCustBaseInfoService;
    private final ComAttachmentManagementMapper managementMapper;
    private final PreApproveService preApproveService;
    private final ApplyRecordDetailsService applyRecordDetailsService;
    private final ApplyConfig applyConfig;
    private final Apply2CaseFeign apply2CaseFeign;
    private final ApplyModifyHistoryService applyModifyHistoryService;
    private final CaseSubmitInfoServiceImpl caseSubmitInfoService;
    private final ArchiveMQService archiveMQService;

    /**
     * 提交案件-发送消息到消费者
     *
     * @return
     */
    @PostMapping("/submitCaseInfo")
    @ApiOperation("提交案件")
    @Transactional(rollbackFor = Exception.class)
    public IResponse submitCaseInfo(@RequestBody CaseSubmitInfoCondition condition) throws Exception {
        // 校验 90天内历史单量＞1 3、原单满足拒绝原因其一（零首付、三方征信瑕疵、虚假职业、虚假材料、身份核实异常、婚姻关系不明、购车目的异常、还款能力不足、隐形负债过高、收入来源无法核实、危险驾驶行为、法院执行、配偶直系历史拒绝、贷款意愿不足、系统评分不足、关联交易、车辆不符合准入标准）
        this.submitInfoService.checkData(condition.getApplyNo());
        // 风控准入判断
        String formalApplyNo = condition.getApplyNo();
        IResponse iResponse = applyProductService.chenkRiskInfo(formalApplyNo);
        if (!CommonConstants.SUCCESS.equals(iResponse.getCode())) {
            return iResponse;
        }
        log.info("临时编号applyNo:{}", condition.getApplyNo());
        //临时编号查询订单信息
        ApplyOrderInfo orderInfoByApplyNo = applyOrderInfoService.getOrderInfoByApplyNo(formalApplyNo);

        //  提交校验
        if(this.checkUserOrderTwo(orderInfoByApplyNo)){
            throw new AfsBaseException("主借人180天内规则被拒绝订单大于0次！");
        }

        if(this.checkCancelOrder(orderInfoByApplyNo)){
            throw new AfsBaseException("90天内被取消单量或撤销单量大于3次！");
        }
        if (this.checkUserOrder(orderInfoByApplyNo)) {
            throw new AfsBaseException("主借人90天内被拒绝订单大于1次！");
        }
        orderInfoByApplyNo.setSellerRealName(condition.getSellerRealName());
        orderInfoByApplyNo.setSellerPhone(condition.getSellerPhone());
        orderInfoByApplyNo.setCreateBy(SecurityUtils.getUsername());
        applyOrderInfoService.updateById(orderInfoByApplyNo);
        //临时编号查询客户信息
        ApplyCustBaseInfo custBaseInfo = applyCustBaseInfoService.getCustBaseInfo(formalApplyNo, ApplyConstants.PRINCIPAL_BORROWER);
        if (ObjectUtil.isNull(orderInfoByApplyNo.getIntoFirstDate())) {
            formalApplyNo = this.applyReportService.getFormalApplyNo(condition.getApplyNo(), orderInfoByApplyNo.getBusinessType(), custBaseInfo.getCertNo());
            log.info("正式编号applyNo:{}", formalApplyNo);
        }
        AfsTransEntity<OrderSubmitInfo> transEntity = submitInfoService.returnMessage(formalApplyNo);
        log.info("--------------------进件报文已推送至审批---------------------------");
        caseSubmitInfoSender.sendForCaseSubmit(transEntity);
        this.applyOrderInfoService.sendApplyMessageInfo(custBaseInfo.getTelPhone());
        return IResponse.success("消息发送成功");
    }

    public Boolean checkUserOrder(ApplyOrderInfo orderInfoByApplyNo) {
        // 查询这个订单的用户数据
        ApplyCustBaseInfo applyCustBaseInfo = applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda().eq(ApplyCustBaseInfo::getApplyNo, orderInfoByApplyNo.getApplyNo()).eq(ApplyCustBaseInfo::getCustRole, ApplyConstants.PRINCIPAL_BORROWER.toString()));
        // 再通过订单的主借人的身份证号查询订单
        List<ApplyCustBaseInfo> list = applyCustBaseInfoService.list(Wrappers.<ApplyCustBaseInfo>query().lambda().eq(ApplyCustBaseInfo::getCertNo, applyCustBaseInfo.getCertNo()).eq(ApplyCustBaseInfo::getCustRole, ApplyConstants.PRINCIPAL_BORROWER.toString()));
        if (list.size() > 0) {
            // 声明一个集合存数据申请编号
            List<String> applyNo = new ArrayList<>();
            for (ApplyCustBaseInfo baseInfo : list) {
                applyNo.add(baseInfo.getApplyNo());
            }
            //  获取90天前的时间
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            Date end = c.getTime();
            String dqrq = format.format(end) + " 23:59:59";//当前日期

            c.add(Calendar.DATE, -90);
            Date start = c.getTime();
            String qyt = format.format(start) + " 00:00:00";//90天前

            // 查询被拒绝的订单  90天以内的
            List<ApplyOrderInfo> orderInfo = applyOrderInfoService.list(Wrappers.<ApplyOrderInfo>query().lambda().in(ApplyOrderInfo::getApplyNo, applyNo).eq(ApplyOrderInfo::getApplyStatus, ApplyConstants.APPLY_STATUS_REFUSE.toString()).between(ApplyOrderInfo::getIntoFirstDate, dqrq, qyt));
            if (orderInfo.size() > 0) {
                List<String> orderApplyNo = new ArrayList<>();
                // 说明被拒绝的单子，然后去看这些单子因为什么被拒绝
                for (ApplyOrderInfo info : orderInfo) {
                    orderApplyNo.add(info.getApplyNo());
                }

                // 再去看看被拒绝原因符合的订单
                List<String> reason = new ArrayList<>();
                // 首付贷“零首付
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.ZERO_DOWN_PAY));
                // 三方征信瑕疵
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.BAD_THIRD_CREDIT));
                //虚假职业
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.FAKE_JOB));
                // 身份核实异常
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.ERR_IDENTITY_CHECK));
                // 婚姻关系不明
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.UN_KNOW_MARRY_STATUS));
                // 购车目的异常
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.ERR_BUY_CAR_PURPOSE));
                // 还款能力不足
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.CAN_NOT_REPAY));
                // 隐性负债较高
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.DEBIT_MORE));
                // 收入来源无法核实
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.UN_KNOW_INCOME));
                // 危险驾驶行为
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.DANGEROUS_DRIVE));
                //法院执行
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.COURT_EXECUTE));
                // 配偶直系为历史被拒客户
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.REFUSE_MARRY));
                // 贷款意愿不足
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.NOT_ENOUGH_ASPIRATION));
                // 系统评分不足
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.NOT_ENOUGH_SYSTEM_SCORE));
                // 关联交易
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.UNION_DEAL));
                // 车辆不符准入标准
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.CAR_NOT_SUPPORT_CRITERION));

                List<WorkflowRecordDetails> details = applyRecordDetailsService.list(Wrappers.<WorkflowRecordDetails>query().lambda().in(WorkflowRecordDetails::getBusinessNo, orderApplyNo).in(WorkflowRecordDetails::getApproveDesc, reason));
                if (details.size() > 0) {
                    Set<String> count = new HashSet<>();
                    for (WorkflowRecordDetails detail : details) {
                        count.add(detail.getBusinessNo());
                    }
                    if (count.size() > 1) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    // 这个校验主借人证件号码查重  且180天内历史订单>0补可以进件
    public Boolean checkUserOrderTwo(ApplyOrderInfo orderInfoByApplyNo){
        // 查询这个订单的用户数据
        ApplyCustBaseInfo applyCustBaseInfo = applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda().eq(ApplyCustBaseInfo::getApplyNo, orderInfoByApplyNo.getApplyNo()).eq(ApplyCustBaseInfo::getCustRole, ApplyConstants.PRINCIPAL_BORROWER.toString()));
        // 再通过订单的主借人的身份证号查询订单
        List<ApplyCustBaseInfo> list = applyCustBaseInfoService.list(Wrappers.<ApplyCustBaseInfo>query().lambda().eq(ApplyCustBaseInfo::getCertNo, applyCustBaseInfo.getCertNo()).eq(ApplyCustBaseInfo::getCustRole, ApplyConstants.PRINCIPAL_BORROWER.toString()));
        if (list.size() > 0) {
            // 声明一个集合存数据申请编号
            List<String> applyNo = new ArrayList<>();
            for (ApplyCustBaseInfo baseInfo : list) {
                applyNo.add(baseInfo.getApplyNo());
            }
            //  获取90天前的时间
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            Date end = c.getTime();
            String dqrq = format.format(end) + " 23:59:59";//当前日期

            c.add(Calendar.DATE, -180);
            Date start = c.getTime();
            String qyt = format.format(start) + " 00:00:00";//90天前

            // 查询被拒绝的订单  90天以内的
            List<ApplyOrderInfo> orderInfo = applyOrderInfoService.list(Wrappers.<ApplyOrderInfo>query().lambda().in(ApplyOrderInfo::getApplyNo, applyNo).eq(ApplyOrderInfo::getApplyStatus, ApplyConstants.APPLY_STATUS_REFUSE.toString()).between(ApplyOrderInfo::getIntoFirstDate, dqrq, qyt));
            if (orderInfo.size() > 0) {
                List<String> orderApplyNo = new ArrayList<>();
                // 说明被拒绝的单子，然后去看这些单子因为什么被拒绝
                for (ApplyOrderInfo info : orderInfo) {
                    orderApplyNo.add(info.getApplyNo());
                }

                // 再去看看被拒绝原因符合的订单
                List<String> reason = new ArrayList<>();
                // 征信不良（主借人）
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.BAD_CREDIT_CUSTOMER));
                // 征信不良（共借人、保证人）
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.BAD_CREDIT_BOND_OR_SPONSOR));
                //多平台借贷或查询次数过多
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.MORE_LOAN));
                // 人行征信查询次数过多
                reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.MORE_CREDIT_QUERY));


                List<WorkflowRecordDetails> details = applyRecordDetailsService.list(Wrappers.<WorkflowRecordDetails>query().lambda().in(WorkflowRecordDetails::getBusinessNo, orderApplyNo).in(WorkflowRecordDetails::getApproveDesc, reason));
                if (details.size() > 0) {
                    Set<String> count = new HashSet<>();
                    for (WorkflowRecordDetails detail : details) {
                        count.add(detail.getBusinessNo());
                    }
                    if (count.size() > 0) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    // 校验 主借人90天内取消的历史单量>3不允许进件
    public boolean checkCancelOrder(ApplyOrderInfo orderInfoByApplyNo){
        // 查询这个订单的用户数据
        ApplyCustBaseInfo applyCustBaseInfo = applyCustBaseInfoService.getOne(Wrappers.<ApplyCustBaseInfo>query().lambda().eq(ApplyCustBaseInfo::getApplyNo, orderInfoByApplyNo.getApplyNo()).eq(ApplyCustBaseInfo::getCustRole, ApplyConstants.PRINCIPAL_BORROWER.toString()));
        // 再通过订单的主借人的身份证号查询订单
        List<ApplyCustBaseInfo> list = applyCustBaseInfoService.list(Wrappers.<ApplyCustBaseInfo>query().lambda().eq(ApplyCustBaseInfo::getCertNo, applyCustBaseInfo.getCertNo()).eq(ApplyCustBaseInfo::getCustRole, ApplyConstants.PRINCIPAL_BORROWER.toString()));
        if(list.size()>0){
            // 声明一个集合存数据申请编号
            List<String> applyNo = new ArrayList<>();
            for (ApplyCustBaseInfo baseInfo : list) {
                applyNo.add(baseInfo.getApplyNo());
            }
            //  获取90天前的时间
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            Date end = c.getTime();
            String dqrq = format.format(end) + " 23:59:59";//当前日期

            c.add(Calendar.DATE, -180);
            Date start = c.getTime();
            String qyt = format.format(start) + " 00:00:00";//90天前

            // 查询被拒绝的订单  90天以内的
            List<String> re=new ArrayList<>();
            re.add(ApplyConstants.APPLY_STATUS_CANCEL.toString());
            re.add(ApplyConstants.APPLY_STATUS_REVOKE.toString());
            List<ApplyOrderInfo> orderInfo = applyOrderInfoService.list(Wrappers.<ApplyOrderInfo>query().lambda().in(ApplyOrderInfo::getApplyNo, applyNo).in(ApplyOrderInfo::getApplyStatus,re).between(ApplyOrderInfo::getIntoFirstDate, dqrq, qyt));
            if(orderInfo.size()>3){
                return true;
            }

        }
        return false;
    }

    /**
     * 加急
     *
     * @param condition
     * @return
     * @throws ParseException
     */
    @PostMapping("/sendForEmergencyCaseSubmit")
    @ApiOperation("加急")
    public IResponse sendForEmergencyCaseSubmit(@RequestBody CaseSubmitInfoCondition condition) throws ParseException {
        AfsTransEntity<UrgentInfoSubmitInfo> urgentInfoSubmitInfoAfsTransEntity = this.submitInfoService.returnEmergencyMessage(condition.getApplyNo());
        caseSubmitInfoSender.sendForEmergencyCaseSubmit(urgentInfoSubmitInfoAfsTransEntity);
        log.info("编号" + condition.getApplyNo() + "已加急");
        return IResponse.success("加急成功");
    }

    /**
     * 资产变更
     *
     * @param condition
     * @return
     * @throws ParseException
     */
    @PostMapping("/sendAssertChangeCaseSubmit")
    @ApiOperation("资产变更")
    @Transactional(rollbackFor = Exception.class)
    public IResponse sendAssertChangeCaseSubmit(@RequestBody CaseSubmitInfoCondition condition) throws ParseException {

        ApplyModifyHistory modifyHistory = applyModifyHistoryService.getModifyHistoryByApplyNo(condition.getApplyNo());
        List<ComAttachmentFile> fileList = new ArrayList<ComAttachmentFile>();
        if (condition.getContractFileVos() != null) {
            queryAndRemove(modifyHistory.getId().toString(), CertTypePictureEnum.CHANGE_OF_ASSETS.getIndex());
            fileList = preApproveService.saveOrUpdateFile(condition.getContractFileVos(), modifyHistory.getId().toString());
        }
        //资产变更后，数据留痕
        applyModifyHistoryService.assertChange(condition.getApplyNo(), AssetChangeEnums.PENDING.getCode());
        AfsTransEntity<ApproveSpecialSubmitInfo> urgentInfoSubmitInfoAfsTransEntity = submitInfoService.returnAssertChangeMessage(condition.getApplyNo(), fileList);
        caseSubmitInfoSender.sendAssertChangeCaseSubmit(urgentInfoSubmitInfoAfsTransEntity);
        log.info("编号" + condition.getApplyNo() + "资产变更信息已提交");
        return IResponse.success("提交成功");
    }

    /**
     * 资产变更上传
     * @param condition
     * @return
     */
    @PostMapping("/uploadFileForAssertChange")
    @ApiOperation("资产变更上传")
    public IResponse uploadFileForAssertChange(@RequestBody CaseSubmitInfoCondition condition){

        ApplyModifyHistory modifyHistory = applyModifyHistoryService.getModifyHistoryByApplyNo(condition.getApplyNo());
        List<ComAttachmentFile> fileList = new ArrayList<ComAttachmentFile>();
        if (condition.getContractFileVos() != null) {
            queryAndRemove(modifyHistory.getId().toString(), CertTypePictureEnum.CHANGE_OF_ASSETS.getIndex());
            fileList = preApproveService.saveOrUpdateFile(condition.getContractFileVos(), modifyHistory.getId().toString());
        }
        return IResponse.success(fileList);
    }

    /**
     * 复议
     *
     * @param condition
     * @return
     * @throws ParseException
     */
    @PostMapping("/saveReconsiderCaseSubmit")
    @ApiOperation("复议")
    public IResponse saveReconsiderCaseSubmit(@RequestBody CaseSubmitInfoCondition condition) throws ParseException {
        List<ComAttachmentFile> fileList = new ArrayList<ComAttachmentFile>();
        // 先校验拒绝原因
        List<String> reason = new ArrayList<>();
        // 首付贷“零首付
        reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.ZERO_DOWN_PAY));
        // 虚假职业
        reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.FAKE_JOB));
        // 虚假材料
        reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.FAKE_FILE));
        // 身份核实异常
        reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.ERR_IDENTITY_CHECK));
        // 婚姻关系不明
        reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.UN_KNOW_MARRY_STATUS));
        //  购车目的异常
        reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.ERR_BUY_CAR_PURPOSE));
        // 还款能力不足
        reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.CAN_NOT_REPAY));
        // 隐性负债较高
        reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.DEBIT_MORE));
        // 收入来源无法核实
        reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.UN_KNOW_INCOME));
        // 法院执行
        reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.COURT_EXECUTE));
        // 贷款意愿不足
        reason.add(AfsEnumUtil.key(ApproveRefuseReasonEnum.NOT_ENOUGH_ASPIRATION));

        List<WorkflowRecordDetails> details = applyRecordDetailsService.list(Wrappers.<WorkflowRecordDetails>query().lambda().in(WorkflowRecordDetails::getBusinessNo, condition.getApplyNo()).notIn(WorkflowRecordDetails::getApproveDesc, reason));
        if (details.size() > 0) {
            throw new AfsBaseException("拒绝的原因属于不可复议范围！");
        }


        if (condition.getContractFileVos() != null) {
            queryAndRemove(condition.getApplyNo(), CertTypePictureEnum.RECONSIDER.getIndex());
            fileList = preApproveService.saveOrUpdateFile(condition.getContractFileVos(), condition.getApplyNo());
        }
        //保存复议信息
        this.submitInfoService.saveReconsideration(condition);
        AfsTransEntity<ReconsiderationDto> afsTransEntity = this.submitInfoService.returnSaveReconsiderMessage(condition.getApplyNo(), fileList);
        this.caseSubmitInfoSender.sendReconsiderCaseSubmit(afsTransEntity);
        log.info("编号:" + condition.getApplyNo() + "已向信审发起复议申请");
        return IResponse.success("提交成功");
    }

    /**
     * 删除之前无效影像件
     *
     * @param id
     * @param type
     * @return
     */
    public String queryAndRemove(String id, String type) {
        ComAttachmentManagement comAttachmentManagement = this.managementMapper.selectOne(Wrappers.<ComAttachmentManagement>query().lambda()
                .eq(ComAttachmentManagement::getUniqueCode, type));
        //先查询
        List<ComAttachmentFile> attachmentFile = this.comAttachmentFileService.list(Wrappers.<ComAttachmentFile>query().lambda().eq(ComAttachmentFile::getBusiNo, id).eq(ComAttachmentFile::getAttachmentCode, comAttachmentManagement.getId().toString()));
        if (attachmentFile.size() > 0) {
            for (ComAttachmentFile comAttachmentFile1 : attachmentFile) {
                this.comAttachmentFileService.removeById(comAttachmentFile1);
                log.info("{}", comAttachmentFile1.getId() + "删除成功");
            }
        }
        return null;
    }

    /**
     * <p>description：</p>
     * 撤回申请
     *
     * @throws ParseException
     * @author ma_xueyu
     * @date 2020年8月31日
     */
    @PostMapping("/callBackCaseSubmit")
    @ApiOperation("撤回")
    public IResponse callBackCaseSubmit(@RequestBody CaseSubmitInfoCondition condition) throws ParseException {
        //查询当前订单在案件端的业务状态,如果案件端业务状态为“待查询”、“任务分配中”，不能直接撤回
        try{
            IResponse response = apply2CaseFeign.getCaseBuinessStateInfo(condition.getApplyNo(), this.makeCaseHeader());
            String caseBuinessStateIn = String.valueOf(response.getData());
            if (AfsEnumUtil.key(BusinessStateInEnum.WAIT_QUERY).equals(caseBuinessStateIn) || AfsEnumUtil.key(BusinessStateInEnum.TASK_ASSIGNING).equals(caseBuinessStateIn)) {
                throw new AfsBaseException("当前订单无法撤回，请稍后再试.");
            }
        }catch (Exception e){
            log.error("查询案件业务状态异常{}",e.getMessage());
            throw new AfsBaseException("当前订单无法撤回，请稍后再试.");
        }
        AfsTransEntity<CallBackApplyDto> afsTransEntity = this.submitInfoService.returnCallBackMessage(condition.getApplyNo());
        this.caseSubmitInfoSender.callBackMessageSender(afsTransEntity);
        log.info("编号:" + condition.getApplyNo() + "已向信审发起撤回申请，报文：" + JSON.toJSONString(afsTransEntity));
        //延迟查询撤回结果
        try {
            Thread.sleep(1500);
        }catch (InterruptedException e){
            log.error("发生异常",e);
        }
        ApplyOrderInfo applyOrderInfo=applyOrderInfoService.getOrderInfoByApplyNo(condition.getApplyNo());
        if(ApplyConstants.APPLY_STATUS_DRAFT.equals(applyOrderInfo.getApplyStatus())||ApplyConstants.CALL_BACK_WAIT_SUBMIT.equals(applyOrderInfo.getApplyStatus())){
            if (ApplyConstants.CALL_BACK_WAIT_SUBMIT.equals(applyOrderInfo.getApplyStatus())){
                //进件查完征信后撤销，案件状态为“撤回待处理”时，生成归档任务,推送信息至归档(申请废弃)
                archiveMQService.archivePushMQ(String.valueOf(applyOrderInfo.getId()), null, applyOrderInfo.getApplyNo(), ArchiveConfig.wworder_refuse);
            }
            return IResponse.success("撤回成功");
        }else{
            throw new AfsBaseException("当前订单无法撤回");
        }

    }

    /**
     * 获取进件请求头
     *
     * @return
     */
    public Map makeCaseHeader() {
        Map<String, String> headers = new HashMap<>();
        headers.put("clientId", applyConfig.getCaseClientId());
        headers.put("clientSecret", applyConfig.getCaseClientSecret());
        return headers;
    }

    @ApiOperation("进件申请-撤销")
    @PostMapping("/applyCancel")
    public IResponse applyCancel(@RequestBody ContractCancelCondition condition) {
        ApplyOrderInfo applyOrderInfo=applyOrderInfoService.getOrderInfoByApplyNo(condition.getApplyNo());
        if (applyOrderInfo != null) {
            AfsTransEntity<RepealDealDto> repealDealDtoAfsTransEntity = this.caseSubmitInfoService.applyCancel(condition);
            caseSubmitInfoSender.applyCancelSender(repealDealDtoAfsTransEntity);
        }else{
            throw new AfsBaseException("订单不存在！");
        }
        return IResponse.success("操作成功");
    }
}
